package com.ztest.statustrans;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class OrderStateService {

    public static List<OrderStatusTransition> orderStatusTransitionList = new ArrayList<>();

    static {

        // 待支付 - 支付 - 待发货
        orderStatusTransitionList.add(OrderStatusTransition.builder().
                fromStatus(OrderStateEnum.WAIT_PAYMENT).
                action(OrderStateChangeActionEnum.PAY).
                toStatus(OrderStateEnum.WAIT_DELIVER).
                build());

        // 待发货 - 发货 - 待确认
        orderStatusTransitionList.add(OrderStatusTransition.builder().
                fromStatus(OrderStateEnum.WAIT_DELIVER).
                action(OrderStateChangeActionEnum.SHIP).
                toStatus(OrderStateEnum.WAIT_RECEIVE).
                build());

        // 待确认 - 确认收货 - 已收货
        orderStatusTransitionList.add(OrderStatusTransition.builder().
                fromStatus(OrderStateEnum.WAIT_DELIVER).
                action(OrderStateChangeActionEnum.DELIVER).
                toStatus(OrderStateEnum.RECEIVED).
                build());

    }


    private void statusTransition(OrderDO orderDO,OrderStateChangeActionEnum actionEnum){

        // 从状态关系中寻找合适的
        OrderStateEnum fromStatus = orderDO.getStatus();
        Optional<OrderStatusTransition> first = orderStatusTransitionList.stream().filter(
                orderStatusTransition -> orderStatusTransition.getFromStatus().equals(fromStatus)
                    && orderStatusTransition.action.equals(actionEnum)
        ).findFirst();
        // 找不到，说明状态不正确
        if (!first.isPresent()){
            throw new RuntimeException("状态错误");
        }

        OrderStateEnum toStatus = first.get().toStatus;
        // 切换订单状态
        orderDO.setStatus(toStatus);
    }

    // 支付
    public void pay(OrderDO orderDO){
        statusTransition(orderDO,OrderStateChangeActionEnum.PAY);
    }


}
